class_name SpellSummonBullet
extends BulletBase

@export var spell_summon_item_config: ItemSpellSummonConfig
@export var summon_target_unit_data: UnitBaseData


func _ready() -> void:
	await get_tree().create_timer(timeout_time).timeout
	
	emit_hit_effect()
	summon_target()
	queue_free()

	
func set_start_velocity(velocity: Vector2):
	self.velocity = velocity
	
	
func emit_hit_effect():
	level.emit_particle(spell_summon_item_config.hit_effect_resource_name, global_position)
	AudioManager.play_sound("sfx_common_fire_explotion")


func summon_target():
	summon_target_unit_data.max_hp = summon_target_unit_data.config.base_life
	summon_target_unit_data.hp = summon_target_unit_data.max_hp
	summon_target_unit_data.pos = global_position
	summon_target_unit_data.face = 1 if randf() < 0.5 else -1
	summon_target_unit_data.is_enemy = self.is_enemy
	if "home_position" in summon_target_unit_data:
		summon_target_unit_data.home_position = global_position
	summon_target_unit_data.summon_source_item = spell_summon_item_config
	
	var unit_inst = level.create_unit_by_unit_data(summon_target_unit_data.duplicate(true)) as CharacterBody2D
	if is_colliding_now(unit_inst):
		place_safely(unit_inst, self.velocity.normalized() * -1 * 4)
	

func is_colliding_now(body: CharacterBody2D) -> bool:
	return body.test_move(body.transform, Vector2.ZERO)
	

func place_safely(unit: CharacterBody2D, step: Vector2):
	var max_checks := 20

	for i in range(max_checks):
		if not is_colliding_now(unit):
			break
		unit.global_position += step
		

func process_hit():
	var bodies = hit_area.get_overlapping_bodies()
	var areas = hit_area.get_overlapping_areas()
	if areas.size() <= 0 and bodies.size() <= 0: return
	
	emit_hit_effect()
	summon_target()
	
	queue_free()


#func set_side(is_enemy: bool = false):
	#if is_enemy:
		#hit_area.set_collision_mask_value(7, true)
		#hit_area.set_collision_mask_value(6, false)
	#else:
		#hit_area.set_collision_mask_value(7, false)
		#hit_area.set_collision_mask_value(6, true)
